//
//  ViewController.m
//  调用系统相册
//
//  Created by whz on 17/3/14.
//  Copyright © 2017年 whz. All rights reserved.
//

#import "ViewController.h"

#define KSCREENW [UIScreen mainScreen].bounds.size.width
#define KSCREENH [UIScreen mainScreen].bounds.size.height
#define IOS8 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ? YES : NO)

@interface ViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate>

@property(nonatomic, strong)UIImageView *headImageView;
@property(nonatomic, strong)UIImageView *imgImageView;
@property(nonatomic, strong)UIButton *getImgBtn;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createUI];
}

- (void)createUI {

    [self.view addSubview:self.headImageView];
    [self.view addSubview:self.imgImageView];
    [self.view addSubview:self.getImgBtn];
}

#pragma mark - method

/**
 保存图片到沙盒

 @param currentImage 当前图片
 @param imageName 图片名称
 */
- (void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName {

    // 设置图片品质
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5); // 1 为不缩放保存，取值（0.0 ~ 1.0）
    // 沙盒路径
    NSString *filePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:filePath atomically:NO];
}

#pragma mark - getImageBtnClick

- (void)getImgBtnClick {

    // 判断是否是IOS8
    if (IOS8) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"获取图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        // 判断是否支持相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
                imagePickerController.delegate = self;
                imagePickerController.allowsEditing = YES;
                imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                
                [self presentViewController:imagePickerController animated:YES completion:^{
                    
                }];
            }];
            [alertController addAction:defaultAction];
        }
        UIAlertAction *defaultAction2 = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing = YES;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            
            [self presentViewController:imagePickerController animated:YES completion:^{
                
            }];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertController addAction:defaultAction2];
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    
    } else {
    
        UIActionSheet *sheet;
        
        // 判断是否支持相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            sheet = [[UIActionSheet alloc] initWithTitle:@"获取图片" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选择", nil];
        
        } else {
        
            sheet = [[UIActionSheet alloc] initWithTitle:@"获取图片" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"从相册中选择", nil];
        }
        [sheet showInView:self.view];
    }
    
}

#pragma mark - UIImagePickerControllerDelegate

/**
 iOS7、iOS8都要调用方法，选择完成后调用该方法
 获取图片缓存并显示

 @param picker picker description
 @param info info description
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {

    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    // 保存图片到本地，上传图片到服务器需要使用
    [self saveImage:image withName:@"whz"];
    
    NSString *filePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"whz.png"];
    
    UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:filePath];

    // 设置图片显示
    [_headImageView setImage:savedImage];
    [_imgImageView setImage:savedImage];
}

/**
 iOS7、iOS8都要调用此方法，按取消时调用

 @param picker picker description
 */
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UIActionSheetDelegate

/**
 iOS7 使用 UIActionSheet

 @param actionSheet actionSheet description
 @param buttonIndex buttonIndex description
 */
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

    NSInteger sourceType = 0;
    
    // 判断是否支持相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        switch (buttonIndex) {
            case 1: // 相机
                sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
                
            case 2: // 相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
                
            default:
                break;
        }
    } else {
    
        if (buttonIndex == 1) {
            
            sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        }
    }
    // 跳转到相机或者相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

#pragma mark - lazyLoad

- (UIImageView *)headImageView {

    CGFloat headImageViewWidth = 60;
    CGFloat headImageViewHeight = 60;
    CGFloat headImageViewX = KSCREENW*0.5-headImageViewWidth*0.5;
    CGFloat headImageViewY = 100;
    
    if (!_headImageView) {
        
        _headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(headImageViewX, headImageViewY, headImageViewWidth, headImageViewHeight)];
        _headImageView.backgroundColor = [UIColor lightGrayColor];
        _headImageView.layer.cornerRadius = headImageViewWidth * 0.5;
        _headImageView.layer.masksToBounds = YES;
    }
    return _headImageView;
}

- (UIImageView *)imgImageView {

    CGFloat imgImageViewX = 20;
    CGFloat imgImageViewY = 180;
    CGFloat imgImageViewWidth = KSCREENW - imgImageViewX*2;
    CGFloat imgImageViewHeight = KSCREENH - imgImageViewY - 100;
    
    
    if (!_imgImageView) {
        
        _imgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(imgImageViewX, imgImageViewY, imgImageViewWidth, imgImageViewHeight)];
        _imgImageView.backgroundColor = [UIColor lightGrayColor];
    }
    return _imgImageView;
}

- (UIButton *)getImgBtn {

    CGFloat getImgWidth = 200;
    CGFloat getImgHeight = KSCREENH - _imgImageView.frame.origin.y - _imgImageView.frame.size.height - 50;
    CGFloat getImgBtnX = KSCREENW*0.5 - getImgWidth*0.5;
    CGFloat getImgBtnY = _imgImageView.frame.size.height + _imgImageView.frame.origin.y + 20;
    
    if (!_getImgBtn) {
        
        _getImgBtn = [[UIButton alloc] initWithFrame:CGRectMake(getImgBtnX, getImgBtnY, getImgWidth, getImgHeight)];
        [_getImgBtn setTitle:@"获取图片" forState:UIControlStateNormal];
        [_getImgBtn setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
        _getImgBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        _getImgBtn.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.2];
        _getImgBtn.layer.cornerRadius = 20;
        _getImgBtn.layer.masksToBounds = YES;
        
        [_getImgBtn addTarget:self action:@selector(getImgBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _getImgBtn;
}

@end
